package com.sens.mybank.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.sens.bean.MybankBill;
import com.sens.common.ActivityLifecycleCallback;
import com.sens.common.Base64;
import com.sens.common.JsonUtils;
import com.sens.common.Log;
import com.sens.common.StringUtil;
import com.sens.database.LiteOrmDBUtil;
import com.sens.ipc.mybank.application.Handle;
import com.sens.network.ApiByHttp;
import com.sens.network.MybankOrderCallback;
import com.sens.tables.MybankOrder;
import com.sens.vo.MybankOrderVo;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.util.EntityUtils;

import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.List;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

public class OrderHelper {
    private ClassLoader classLoader;
    private Handle handle;
    private Context context;

    private Activity H5Activity;

//    private static final long EACH_TIME = 5 * 1000;

    private static long lastRunTime;
    private boolean isJustQuery;
    private boolean collectionAble;
    private boolean start;
    private boolean threadRunning;

    public Context getContext() {
        return context;
    }

    public OrderHelper(Context context, Handle handle) throws Throwable {
        this.context = context;
        this.handle = handle;
        this.classLoader = context.getClassLoader();
        Class HttpHost = classLoader.loadClass(new String(Base64.decode("b3JnLmFwYWNoZS5odHRwLkh0dHBIb3N0")));
        Class HttpRequest = classLoader.loadClass(new String(Base64.decode("b3JnLmFwYWNoZS5odHRwLkh0dHBSZXF1ZXN0")));
        Class HttpContext = classLoader.loadClass(new String(Base64.decode("b3JnLmFwYWNoZS5odHRwLnByb3RvY29sLkh0dHBDb250ZXh0")));
        XposedHelpers.findAndHookMethod(new String(Base64.decode("Y29tLmFsaXBheS5hbmRyb2lkLnBob25lLm1ycGMuY29yZS5BbmRyb2lkSHR0cENsaWVudA")), classLoader, new String(Base64.decode("ZXhlY3V0ZQ")), HttpHost, HttpRequest, HttpContext, executeHooker);
        ((Application) context).registerActivityLifecycleCallbacks(lifecycleCallback);
    }

    private ActivityLifecycleCallback lifecycleCallback = new ActivityLifecycleCallback() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            super.onActivityCreated(activity, savedInstanceState);
            if (threadRunning)
                if (new String(Base64.decode("Y29tLmFsaXBheS5tb2JpbGUubmVidWxhY29yZS51aS5INUFjdGl2aXR5")).equals(activity.getClass().getName())) {
                    Log.i("获取到activity");
                    H5Activity = activity;
                }
        }

//        @Override
//        public void onActivityDestroyed(Activity activity) {
//            super.onActivityDestroyed(activity);
//            if (new String(Base64.decode("Y29tLmFsaXBheS5tb2JpbGUubmVidWxhY29yZS51aS5INUFjdGl2aXR5")).equals(activity.getClass().getName())) {
//                H5Activity = null;
//            }
//        }
    };

//    private Runnable startRunnable = new Runnable() {
//        @Override
//        public void run() {
//            threadRunning = true;
//            while (start) {
//                try {
//                    long time = System.currentTimeMillis();
//                    if (time - lastRunTime < EACH_TIME) continue;
//                    lastRunTime = time;
//                    queryOrder();
////                    Thread.sleep(EACH_TIME);
//                } catch (Throwable throwable) {
//                    throwable.printStackTrace();
//                }
//            }
//            threadRunning = false;
//        }
//    };

    public void start() {
        if (!collectionAble || start || threadRunning) return;
        start = true;
//        new Thread(startRunnable).start();
        queryOrder();
    }

    public void stop() {
        if (!start) return;
        start = false;
    }

    public void setCollectionAble(boolean collectionAble) {
        if (this.collectionAble == collectionAble) return;
        this.collectionAble = collectionAble;
        if (collectionAble && start && !threadRunning)
//            new Thread(startRunnable).start();
            queryOrder();
    }

    public String getUserId() {
        try {
            Class LoggingSPCacheClass = classLoader.loadClass(new String(Base64.decode("Y29tLmFsaXBheS5tb2JpbGUuY29tbW9uLmxvZ2dpbmcudXRpbC5Mb2dnaW5nU1BDYWNoZQ")));
            Method getInstance = LoggingSPCacheClass.getMethod(new String(Base64.decode("Z2V0SW5zdGFuY2U")));
            Method getString = LoggingSPCacheClass.getMethod(new String(Base64.decode("Z2V0U3RyaW5n")), String.class, String.class);
            return (String) getString.invoke(getInstance.invoke(null), new String(Base64.decode("dXNlcklE")), null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public void justQueryOrder() {
        isJustQuery = true;
        queryOrder();
    }

    private boolean isHookStart;

    private void queryOrder() {
        lastRunTime = System.currentTimeMillis();
        threadRunning = true;
        isHookStart = true;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(new String(Base64.decode("bXliYW5rOi8vaDVjb250YWluZXIvaW5kZXg/dXJsPWh0dHBzJTNhJTJmJTJmcmVuZGVyLmFsaXBheS5jb20lMmZwJTJmaDUlMmZiaWxsRm9yTXliYW5rJTJmd3d3JTJmaW5kZXguaHRtbCZzaG93T3B0aW9uTWVudT1OTyZjYW5QdWxsRG93bj1OTw"))));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    class CloseRunnable implements Runnable {
        Activity activity;

        public CloseRunnable(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (activity == null) return;
            activity.finish();
            activity = null;
            if (!start) return;
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (System.currentTimeMillis() - lastRunTime < 10 * 1000) return;
            if (start) queryOrder();
        }
    }

    private XC_MethodHook executeHooker = new XC_MethodHook() {
        @Override
        protected void afterHookedMethod(MethodHookParam param) throws Throwable {
            super.afterHookedMethod(param);
            if (!(isJustQuery || threadRunning)) return;
            if (!(param.args[1] instanceof HttpPost)) return;
            HttpPost post = (HttpPost) param.args[1];
            String bizType = StringUtil.getUrlParam(URLDecoder.decode(EntityUtils.toString(post.getEntity()), "utf-8"), new String(Base64.decode("b3BlcmF0aW9uVHlwZQ")));
            Log.i("bizType:" + bizType);
            if (!new String(Base64.decode("Y29tLm15YmFuay5ia3N0bXRjb3JlLmJpei5zZXJ2aWNlLk1vYmlsZVRyYWRlQmlsbFF1ZXJ5U2VydmljZS5wYWdlVHJhZGVTdG10")).equals(bizType))
                return;
            Log.i("收到信息：" + H5Activity);
            if (H5Activity != null && isHookStart) {
                new Thread(new CloseRunnable(H5Activity)).start();
                isHookStart = false;
//                if (threadRunning)
//                    ApplicationUtil.moToBackground(context);
            }
            H5Activity = null;
            HttpResponse response = (HttpResponse) param.getResult();
            String responseString = EntityUtils.toString(response.getEntity());
            ByteArrayEntity byteArrayEntity = new ByteArrayEntity(responseString.getBytes("utf-8"));
            response.setEntity(byteArrayEntity);
            Log.i("收到数据:" + responseString);
            new Thread(new UploadRunnable(responseString)).start();
            threadRunning = false;
        }
    };

    private class UploadRunnable implements Runnable {
        private String responseString;

        public UploadRunnable(String responseString) {
            this.responseString = responseString;
        }

        @Override
        public void run() {
            MybankBill mybankBill = JsonUtils.parserJson2Bean(responseString, MybankBill.class);
            MybankBill.Result result = mybankBill.getResult();
            if (!result.isSuccess()) return;
            List<MybankBill.Result.PageList.PageElements> pageElementsList = result.getPageList().getPageElements();
            Log.i("size:" + pageElementsList.size());
            for (MybankBill.Result.PageList.PageElements pageElements : pageElementsList) {
                String orderId = pageElements.getBizNo();
                double amount = pageElements.getTradeAmt().getAmount();
                if (amount < 0) continue;//订单
                if (!isJustQuery && LiteOrmDBUtil.getGlobalDBUtil(context).queryOneByWhere(MybankOrder.class, "orderId", orderId) != null)
                    continue;
                MybankOrderVo vo = new MybankOrderVo();
                vo.setTime(pageElements.getTradeGmtModified());
                vo.setOrderId(orderId);
                vo.setAmount(amount);

                vo.setCurrencyCode(pageElements.getTradeAmt().getCurrencyCode());
                vo.setTradeRemark(pageElements.getTradeRemark());
                vo.setOwnerName(pageElements.getOwnerName());
                vo.setOwnerCardNo(pageElements.getOwnerCardNo());
                vo.setTradeNo(pageElements.getTradeNo());
                vo.setTradeName(pageElements.getTradeName());
                vo.setOppositeCardNo(pageElements.getOppositeCardNo());
                vo.setOppositeName(pageElements.getOppositeName());
                handle.addOrder(vo);
                if (isJustQuery) {
                    isJustQuery = false;
                    return;
                }
                MybankOrder mybankOrder = OrderUtil.createMybankOrder(vo);
                LiteOrmDBUtil.getGlobalDBUtil(context).save(mybankOrder);
                ApiByHttp.getInstance().uploadMybankOrder(mybankOrder, new MybankOrderCallback(context, mybankOrder.getOrderId()) {
                    @Override
                    protected void onComplete(boolean isSuccess, String orderId, String msg) {
                        super.onComplete(isSuccess, orderId, msg);
                        handle.noticeMessage(msg + ":" + orderId);
                    }
                });
            }
        }
    }
}
